package socket;

import java.io.ByteArrayOutputStream;

/**
 * @author huyong
 * @version 1.0.0
 * @description
 * @date 2015/5/26 14:30
 */
public class ReceiveSocket extends Thread{
	@Override
	public void run() {
		while(true){
			if(null == InitSocket.map.get("done")){
				continue;
			}
			try {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				byte[] header = new byte[2];
				int count = InitSocket.is.read(header);
				if(count!=2){
					System.err.println("读取报文长度出错。预期长度为2,实际长度为" + count);
				}else{
					bos.write(header);
				}
				String headerString = new String(header, "UTF-8");
				int resLength = Integer.parseInt(headerString);
				byte[] body = new byte[resLength];
				count = InitSocket.is.read(body);
				if(count!=resLength){
					System.err.println("读取报文长度出错。预ji长度为" + resLength + ",实际长度为" + count);
				}else{
					bos.write(body);
				}
				System.out.println(new String(body, "UTF-8"));
			} catch (Exception ex) {
				if(null != InitSocket.map.get("done")){
					InitSocket.map.remove("done");
				}
				ex.printStackTrace();
			}
		}
	}
}
